package com.lin.netty.improve.协议;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Scanner;

@Slf4j
public class TCPClientTest {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup workers = new NioEventLoopGroup();
        Channel channel = bootstrap
                .group(workers)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        log.debug("初始化通道：{}", ch);
                        ch.pipeline().addLast("log",new LoggingHandler());
                        ch.pipeline().addLast("encoder",new StringEncoder());
                        ch.pipeline().addLast("in1", new SimpleChannelInboundHandler<ByteBuf>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                                log.debug("收到数据：{}",msg.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                })
                .connect("127.0.0.1", 1000)
                .sync()
                .channel();
        log.debug("连接成功：{}", channel);

        while (true){
            Scanner scanner = new Scanner(System.in);
            String msg = scanner.nextLine();

            if ("q".equals(msg)) {
                workers.shutdownGracefully();
                channel.closeFuture().sync();
                break;
            }

            channel.writeAndFlush(msg);
        }
    }
}
